package com.auth.service.impl;

import com.auth.custom.CustomUser;
import com.auth.model.system.SysUser;
import com.auth.service.SysMenuService;
import com.auth.service.SysUserService;
import exception.BusinessException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:Tangjiachang
 * @Date 2023/7/16
 * @Description:
 */
@Component
public class UserDetailServiceImpl implements UserDetailsService {
    private final SysUserService sysUserService;

    private final SysMenuService sysMenuService;

    /**
     * 注入
     *
     * @author Tangjiachang
     * @date 2023/7/22 13:37
     * @param sysUserService:
	 * @param sysMenuService:
     * @return null
     **/
    public UserDetailServiceImpl(SysUserService sysUserService, SysMenuService sysMenuService) {
        this.sysUserService = sysUserService;
        this.sysMenuService = sysMenuService;
    }

    /**
     * 加载用户名
     *
     * @author Tangjiachang
     * @date 2023/7/22 13:38
     * @param username:
     * @return UserDetails
     **/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getUserByUserName(username);
        if (null == sysUser) {
            throw new BusinessException(201, "用户不存在");
        }
        if (sysUser.getStatus() == 0) {
            throw new BusinessException(201, "账号已停用");
        }
        // 根据用户id查询用户操作的权限数据
        List<String> userPerms = sysMenuService.findUserPermsByUserId(sysUser.getId());
        // 封装最终的权限数据
        List<SimpleGrantedAuthority> authList = userPerms
                .stream()
                .map(item -> new SimpleGrantedAuthority(item.trim()))
                .collect(Collectors.toList());
        return new CustomUser(sysUser, authList);
    }
}
